package com.secure.orm.service.billPay.impl;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.secure.common.util.PayUtil;
import com.secure.orm.enums.PayType;
import com.secure.orm.enums.PaymentOrderType;
import com.secure.orm.enums.ThirdPayNotifyType;
import com.secure.orm.model.PayOrder;
import com.secure.orm.model.response.ViewData;
import com.secure.orm.service.PayOrderService;
import com.secure.orm.service.billPay.NotifyService;
import com.secure.orm.thirdPay.BaseThirdPay;
import com.secure.orm.thirdPay.alipay.Alipay;
import com.secure.orm.thirdPay.bill99.Bill99Config;

@Service("notifyService")
public class NotifyServiceImpl implements NotifyService {
	protected Log logger = LogFactory.getLog(NotifyServiceImpl.class);
	private ExecutorService pool = Executors.newFixedThreadPool(10); 
	@Autowired
	private BaseThirdPay baseThirdPay;
	@Autowired
	private PayOrderService payOrderService;
	
	
	@Override
	public ViewData handleNotify(Map<String, String> requestParamsMap, PayType payType, ThirdPayNotifyType thirdPayNotifyType) throws Exception {
		ViewData vd = null;
		try {
			String orderId = "", tradeStatus = "", thirdTradeNo = "", buyerId = "", bankType = "", bankBillNo = "", payInfo = "";
			Double price = 0d;
			int status = PaymentOrderType.SCCUESS.getValue();
			if (PayType.Alipay.getValue().equals(payType.getValue())) {
				orderId = requestParamsMap.get(Alipay.ALIPAY_OUT_TRADE_NO);
				tradeStatus = requestParamsMap.get(Alipay.ALIPAY_TRADE_STATUS);
				thirdTradeNo = requestParamsMap.get(Alipay.ALIPAY_TRADE_NO);
				price = Double.valueOf(PayUtil.divideToDouble(requestParamsMap.get(Alipay.ALIPAY_TOTAL_FEE), "100"));
				buyerId = requestParamsMap.get(Alipay.ALIPAY_BUYER_ID);
			} else if (PayType.Tenpay.getValue().equals(payType.getValue())) {
				tradeStatus = requestParamsMap.get("trade_state");
				orderId = requestParamsMap.get("out_trade_no");
				thirdTradeNo = requestParamsMap.get("transaction_id");
				price = Double.valueOf(PayUtil.divideToDouble(requestParamsMap.get("total_fee"), "100"));
				buyerId = requestParamsMap.get("buyer_alias");
				
				bankType = requestParamsMap.get("bank_type");
				bankBillNo = requestParamsMap.get("bank_billno");
				payInfo = requestParamsMap.get("pay_info");

			} else if (PayType.Bill99.getValue().equals(payType.getValue())) {
				orderId = requestParamsMap.get(Bill99Config.out_trade_no);
				tradeStatus = requestParamsMap.get(Bill99Config.trade_status);
				thirdTradeNo = requestParamsMap.get(Bill99Config.trade_no);
				price = Double.valueOf(PayUtil.divideToDouble(requestParamsMap.get(Bill99Config.total_fee), "100"));
				buyerId = requestParamsMap.get(Bill99Config.buyer_id);

				bankType = requestParamsMap.get("bankId");
				bankBillNo = requestParamsMap.get("bankDealId");
				payInfo = requestParamsMap.get("errCode");
			}
			logger.info("handleNotify orderId:" + orderId + ", tradeNo:"
					+ thirdTradeNo + ", tradeStatus:" + tradeStatus
					+ ", payType:" + payType.name() + ", thirdPayNotifyType:"
					+ thirdPayNotifyType.name() + ", price:" + price
					+ ", pay info:" + payInfo + ", bany_type:"
					+ (bankType == null ? "" : bankType) + ", bank BillNo:"
					+ (bankBillNo == null ? "" : bankBillNo));
			vd = baseThirdPay.handleResponse(requestParamsMap,PayType.getThirdPayClassName(payType),thirdPayNotifyType);
			if(vd.getCode()==-1){
				status = PaymentOrderType.FAIL.getValue();
				return vd;
			}
			//更新订单状态
			final PayOrder payOrder = new PayOrder();
			try {
				PayOrder por = payOrderService.findByOrderId(orderId);
				if (por != null) {
					payOrder.setId(por.getId());
				}
				payOrder.setOrderId(orderId);
				payOrder.setOrderAmount(price);
				payOrder.setStatus(status);
				payOrder.setThirdTradeNO(thirdTradeNo);
				payOrderService.save(payOrder, true);
				logger.info(buyerId);
			} catch (DataAccessException e) {
				vd.setCode(0);
				return vd;
			}
			
			//添加日志
			
			//通知业务组接口,需要异步处理
			pool.execute(new Runnable() {
	            @Override
	            public void run() {
	                notityOther(payOrder);
	            }
	        });
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vd;
	}
	
	
	// 第三方支付 主动通知后，在通知其他业务组的项目
    public ViewData notityOther(final PayOrder payOrder){
    	System.out.println("22");
		return null;
    }
	
	
}
